#include <CLikelihood.h>

void CLikelihood::Mean() {
  mean = 0;
  for (int i=0;i<likelihood.size();i++)
    mean+=likelihood[i].likelihood;
  
  mean/=(double)likelihood.size();
}

void CLikelihood::Std() {
  Mean();
  
  std = 0;
  for (int i=0;i<likelihood.size();i++)
    std+=pow(likelihood[i].likelihood - mean, 2.0);
  
  std=std/(double)likelihood.size();
}

void CLikelihood::Conditional() {
  
  CParameters params = likelihood[0];
  for (int i=0;i<binx;i++) {
    Px.Val[i] = 0;
    Px.IndexScaled[i] = params.zfrom + params.dz*i;
    for (int j=0;j<biny;j++) {
	Px.Val[i] += likelihood[i+j*binx].likelihood;
    }
    Px.Val[i] /=(double)biny;
  }
  
  for (int i=0;i<biny;i++) {
    Py.Val[i] = 0;
    Py.IndexScaled[i] = params.VDfrom + params.dVD*i;
    for (int j=0;j<binx;j++) {
      Py.Val[i] += likelihood[j+i*binx].likelihood;
    }
    Py.Val[i] /=(double)binx;
  }
  
  
}

void CLikelihood::ToLikelihood() {
  
  Std();
  cout << "std, mean :" << std  << ", " << mean << endl; 
  
  for (int i=0;i<likelihood.size();i++)
    likelihood[i].likelihood/=sqrt(std);
  
  double m = 1E20;
  
  for (int i=0;i<likelihood.size();i++)
    m = min(likelihood[i].likelihood, m);
  
    cout << "min: " << m << endl;
    
    for (int i=0;i<likelihood.size();i++)
      likelihood[i].likelihood = exp(-(likelihood[i].likelihood-m));
    
    
    Conditional();
}


void CLikelihood::SaveText(string filename) {
  
  ofstream f(filename.c_str(), ios::out);
  for (int i=0;i<binx; i++)  {
    
    for (int j=0;j<biny; j++) {
      CParameters& p = likelihood[ i + j *binx];
	f << p.z << " " << p.VD << " " << p.likelihood << endl;
    }
    f << " " <<endl;
      
  }
  
  f.close();
}

